package cn.tjad.tjad2.module.user.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.qiandian.android.base.fragment.BaseFragment;

import java.io.Serializable;
import java.util.List;

import cn.tjad.tjad2.module.common.adapter.StringListAdapter;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.Department;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.listener.OnItemClickListener;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.RouteUtils;

public class MemberDepartmentFragment extends BaseFragment implements OnItemClickListener {

    private RecyclerView recyclerView;
    private StringListAdapter adapter;

    @Override
    public View getContentView(LayoutInflater inflater) {
        recyclerView = new RecyclerView(getContext());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        return recyclerView;
    }

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            List<Serializable> data = (List<Serializable>) bundle.getSerializable("displayList");
            if (data != null) {
                adapter = new StringListAdapter(data);
                adapter.setOnItemClickListener(this);
                recyclerView.setAdapter(adapter);
            } else {
                getActivity().finish();
            }
        }
    }

    @Override
    public void onItemClick(View parentView, View itemView, int position) {
        StringListAdapter adapter = (StringListAdapter) recyclerView.getAdapter();
        if (adapter != null) {
            Serializable item = adapter.getItemData(position);
            if (item instanceof Department) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(Keys.BODY, ((Department) item).userList);
                RouteUtils.toPage(getContext(), PageId.USER_LIST, bundle);
            } else if (item instanceof User) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("user", item);
                RouteUtils.toPage(getContext(), PageId.MEMBER_USER_DETAIL, bundle);
            }
        }
    }
}
